package com.coderman.spring.aopscale.utils;


import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * @author fanchunshuai
 * @desc AES 加密工具类
 */
public class AESUtil {

    private static final Logger logger = LoggerFactory.getLogger(AESUtil.class);
    private static final String KEY_ALGORITHM = "AES";
    //默认的加密算法
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
    //AES加密密码

    /**
     * AES 加密操作
     *
     * @param content 待加密内容
     * @return 返回Base64转码后的加密数据
     */
    public static String encrypt(String content) throws Exception{
        if(StringUtils.isBlank(content) || "null".equals(content)){
            logger.error("加密失败：加密源数据为空或者null");
            return null;
        }
        // 创建密码器
        Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);

        byte[] byteContent = content.getBytes("utf-8");
        // 初始化为加密模式的密码器
        cipher.init(Cipher.ENCRYPT_MODE, getSecretKey());
        // 加密
        byte[] result = cipher.doFinal(byteContent);
        //通过Base64转码返回
        return Base64.getEncoder().encodeToString(result);

    }

    /**
     * AES 解密操作
     *
     * @param content
     * @return
     */
    public static String decrypt(String content) {
        if(StringUtils.isBlank(content) || "null".equals(content) ){
            logger.error("解密失败：解密源数据位空或者null");
            return "";
        }

        try {
            //实例化
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);

            //使用密钥初始化，设置为解密模式
            cipher.init(Cipher.DECRYPT_MODE, getSecretKey());

            //执行操作
            byte[] result = cipher.doFinal(Base64.getDecoder().decode(content));

            return new String(result, "utf-8");
        } catch (Exception ex) {
            logger.error("=======解密" + content + "字段发生异常======" , ex);
            return "";
        }
    }

    /**
     * 生成加密秘钥
     *
     * @return
     */
    private static SecretKey  getSecretKey() throws Exception{
        KeyGenerator generator = KeyGenerator.getInstance(KEY_ALGORITHM);
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        //secureRandom.setSeed(AES_PSD.getBytes());
        generator.init(128,secureRandom);
        return  generator.generateKey();
    }
}
